import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '../views/login.vue'
import detail from '../views/detail.vue'
import layout from '../views/layout.vue'
import register from '../views/register.vue'
import article from '../views/article.vue'
import like from '../views/like.vue'
import collect from '../views/collect.vue'
import user from '../views/user.vue'
import { getToken } from '@/utils/storage'
Vue.use(VueRouter)
const routes = [
  { path: '/login', component: login },
  { path: '/register', component: register },
  { path: '/detail/:id', component: detail },
  {
    path: '/',
    component: layout,
    redirect: '/article',
    children: [
      { path: 'article', component: article },
      { path: 'like', component: like },
      { path: 'collect', component: collect },
      { path: 'user', component: user }
    ]
  }
]
const router = new VueRouter({
  routes
})
const whiteList = ['/login', '/register'] // 白名单列表，记录无需权限访问的所有页面
router.beforeEach((to, from, next) => {
  const token = getToken()
  // 如果有token，直接放行
  if (token) {
    next()
  } else {
    // 没有token的人, 看看你要去哪
    // (1) 访问的是无需授权的页面（白名单），也是放行
    //     就是判断，访问的地址，是否在白名单数组中存在 includes
    if (whiteList.includes(to.path)) {
      next()
    } else {
      // (2) 否则拦截到登录
      next('/login')
    }
  }
})

export default router
